<template>
  <a-modal :title="title" :visible="showModel" :width="width" @cancel="onClose" @ok="ok">
    <p />
    <div
      :id="'container_' + mapKey"
      :key="mapKey"
      :style="'width:98%;height:500px;margin-left:20px;margin-bottom:50px'"
    />
    <!-- <p>经度：{{ longitude }} 纬度：{{ latitude }} 地址：{{ address }}</p> -->
    <!-- <a-button
      type="primary"
      icon="environment"
      :loading="loading"
    >定位</a-button>-->
    <a-input-search
      v-model="searchAdress"
      style="width: 300px"
      placeholder="地址搜索"
      enter-button
      @search="onSearch"
    />
    <a-list style="height: 200px;overflow: scroll">
      <!-- <a-list-item
        v-for="(addr, idx) in narAddress"
        :key="idx"
        @click="selectAddr(addr)"
      >
        <h3>{{ addr.name }} <a-tag>{{ addr.category }}</a-tag>
        </h3>
        <br>
        <h7>地址：{{ addr.address }}</h7>
      </a-list-item>-->
    </a-list>
  </a-modal>
</template>

<script>
import Vue from 'vue'
	import {
		VueJsonp
	} from 'vue-jsonp'
	Vue.use(VueJsonp)
	const vm = new Vue()
export default {
  name: "TXMap",
  props: {
    show: {
      default: false
    },
    width: {
      default: 680
    },
    title: {
      default: ""
    }
  },
  data() {
    return {
      mapKey: new Date().getTime(),
      /** loading **/
      loading: false,
      /** 地址 **/
      searchAdress: "百花山路",
      detailcontent: "这是我当前的位置",
      address: "",

      longitude: "", // 经度
      latitude: "", // 纬度
      city: "",
      /** 定位 **/
      geolocation: null,

      myLatlng: null,
      map: null,
      geo: null,

      markerSelect: null,
      labelMarkerSelect: null,
      narAddress: [],
      zoom: 13,
      allAddress: ""
    };
  },
  computed: {
    showModel: {
      get: function() {
        this.setMap();
        return this.show;
      },
      set: function() {}
    }
  },
  watch: {},
  mounted() {
    this.setMap();
    // this.buttonPosition();
  },
  created() {
    // eslint-disable-next-line no-undef
    this.geolocation = new qq.maps.Geolocation(
      "M6DBZ-QDQKU-OV3VS-2HEJJ-UMTXZ-NTBY3",
      "shopMap"
    );
    this.getlocation()
    // eslint-disable-next-line no-undef
    this.geo = new qq.maps.Geocoder();
  },
  methods: {
    getlocation() {
      var data = {
        key: "M6DBZ-QDQKU-OV3VS-2HEJJ-UMTXZ-NTBY3" //这个key就是你申请的密钥
      };
      var url = "https://apis.map.qq.com/ws/location/v1/ip"; //这个就是地理位置信息的接口
      data.output = "jsonp";
      vm.$jsonp(url, data)
        .then(res => {
          this.latitude = res.result.location.lat
          this.longitude = res.result.location.lng
        })
        .catch(error => {
        })
    },
    /** **/
    onClose() {
      this.$emit("close");
    },
    initMap(location = null) {
      // let _this = this
      if (!location) {
        // this.getPosition();
        // setTimeout(function () {
        //   _this.setMap()
        // }, 3000)
      } else {
        this.longitude = location.lng;
        this.latitude = location.lat;
        this.setMap();
        // setTimeout(function () {
        //   _this.setMap()
        // }, 3000)
      }
    },

    /** ***/
    ok() {
      const location = {
        lat: this.latitude,
        lng: this.longitude
      };
      this.$emit("position", location);
      this.$emit("close");
    },

    /** 进行地址搜索 **/
    onSearch() {
      const _this = this;
      // returnCitySN["cip"]+','+returnCitySN["cname"] returnCitySN['cname'] 在index.html 引入了<script src="http://pv.sohu.com/cityjson?ie=utf-8">
      // eslint-disable-next-line no-undef
      let search =
        returnCitySN["cname"].split("省")[0] +
        "省," +
        returnCitySN["cname"].split("省")[1];
      if (_this.searchAdress) {
        search += "," + _this.searchAdress;
      }
      _this.geo.getLocation(search); // 地址
      _this.geo.setComplete(function(res) {
        _this.latitude = res.detail.location.lat;
        _this.longitude = res.detail.location.lng;
        _this.detailcontent = res.detail.address;
        _this.address = res.detail.address;
        _this.setMap();
        _this.detailcontent = "这是我当前的位置";

        // eslint-disable-next-line no-undef
        const center = new qq.maps.LatLng(_this.latitude, _this.longitude);
        // eslint-disable-next-line no-undef
        var geocoder = new qq.maps.Geocoder({
          complete(res) {
            _this.narAddress = res.detail.nearPois;
          }
        });
        geocoder.getAddress(center);
      });
    },

    /** 按钮 **/
    buttonPosition() {
      this.loading = true;
      this.getPosition();
    },

    // 第一部分
    /** 定位获得当前位置信息 **/
    getMyLocation() {
      // eslint-disable-next-line no-undef
      this.geolocation = new qq.maps.Geolocation(
        "M6DBZ-QDQKU-OV3VS-2HEJJ-UMTXZ-NTBY3",
        "shopMap"
      );
      this.getPosition();
    },
    /** 执行定位 **/
    getPosition() {
      // this.geolocation.getIpLocation(this.showPosition, this.showErr)
      this.geolocation.getLocation(this.showPosition, this.showErr); // 或者用getLocation精确度比较高
    },
    showPosition(position) {
      const _this = this;
      this.latitude = position.lat; // 经度
      this.longitude = position.lng; // 纬度
      this.city = position.city;
      // eslint-disable-next-line no-undef
      const center = new qq.maps.LatLng(this.latitude, this.longitude);
      // eslint-disable-next-line no-undef
      var geocoderPos = new qq.maps.Geocoder({
        complete(res) {
          _this.narAddress = res.detail.nearPois;
        }
      });
      geocoderPos.getAddress(center);
      this.setMap();
      // 消除loading
      this.loading = false;
      this.address = position.province + position.city;
    },
    showErr() {
      this.getPosition(); // 定位失败再请求定位，测试使用
    },
    // 第二部分
    /** 位置信息在地图上展示 **/
    setMap() {
      const _this = this;
      // 步骤：定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
      // 设置地图中心点
      // eslint-disable-next-line no-undef
      const center = new qq.maps.LatLng(this.latitude, this.longitude);
      // 定义工厂模式函数
      var myOptions = {
        zoom: _this.zoom, // 设置地图缩放级别
        center: center, // 设置中心点样式
        // eslint-disable-next-line no-undef
        mapTypeId: qq.maps.MapTypeId.ROADMAP // 设置地图样式详情参见MapType
      };
      // //获取dom元素添加地图信息
      // eslint-disable-next-line no-undef
      const map = new qq.maps.Map(
        document.getElementById("container_" + _this.mapKey),
        myOptions
      );
      // 第三部分
      /** 给定位的位置添加图片标注 **/
      // eslint-disable-next-line no-undef,no-unused-vars
      var marker = new qq.maps.Marker({
        position: center,
        map: map
      });
      // 给定位的位置添加文本标注
      // eslint-disable-next-line no-undef,no-unused-vars,no-redeclare
      // var marker = new qq.maps.Label({
      //   position: center,
      //   map: map,
      //   content: this.detailcontent
      // })
      /** 信息标记 **/
      // eslint-disable-next-line no-undef
      var infoWin = new qq.maps.InfoWindow({
        map: map
      });
      /** 点击后生成的地表名称 **/
      // let address = '此地'
      // eslint-disable-next-line no-undef
      var geocoder = new qq.maps.Geocoder({
        complete(res) {
          _this.allAddress = res;
          _this.$emit("addressInfo", _this.allAddress);
          _this.address = res.detail.address; // 这里是你点击之处根据经纬度返回的地点名称
          _this.narAddress = res.detail.nearPois;
          _this.longitude = res.detail.location.lng;
          _this.latitude = res.detail.location.lat;
        }
      });
      // 第四部分
      /** 给地图添加点击事件，并获取鼠标点击的经纬度 **/
      // eslint-disable-next-line no-undef,no-unused-vars
      qq.maps.event.addListener(map, "click", function(event) {
        this.longitude = event.latLng.getLng();
        this.latitude = event.latLng.getLat();

        geocoder.getAddress(event.latLng);
        setTimeout(() => {
          infoWin.open();
          infoWin.setContent(
            `<div style="text-align:center;white-space:nowrap;">${address}</div>`
          );
          infoWin.setPosition(event.latLng);
        }, 200);
      });
    },
    /** 选中地址 **/
    selectAddr(addr) {
      const _this = this;
      this.longitude = addr.latLng.lng;
      this.latitude = addr.latLng.lat;
      _this.address = addr.address;
      _this.zoom = 17;
      _this.detailcontent = addr.name;
      this.setMap();
    }
  }
};
</script>

<style scoped>
</style>
